package com.example.test013;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 测试ScheduledExecutorService接口中延迟执行任务和重复执行任务功能
 */
public class ScheduledExecutorServiceDemo01 {
    public static void main(String[] args) {
//      1.具备延迟执行任务的线程池对象  （线程池里面最多有三个）
        ScheduledExecutorService es = Executors.newScheduledThreadPool(3, new ThreadFactory() {
            int num=1;
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"自定义线程名"+num++);
            }
        });

//      2.创建多个任务对象，提交任务，每个任务延迟执行
            es.scheduleAtFixedRate(new MyRunnable(1), 2, 2, TimeUnit.SECONDS);

//      main方法结束标志
        System.out.println("over");
    }
}

class MyRunnable implements Runnable {

    private int id;

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        try {
//          模拟任务的执行时间比较长
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(name + "执行了任务编号" + id);
    }

    public MyRunnable(int id) {
        this.id = id;
    }

}
